package br.usp.ime.dojo.client;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.VerticalPanel;

public class UserListWidget extends Composite {
	private final int REFRESH_TIME = 1000;
	private DojoRoomServiceAsync roomInfoAsync;
	private String dojoRoomName;
	private VerticalPanel vPanel;
	private FlexTable userList;

	public UserListWidget(String name) {
		
		dojoRoomName = name;
		roomInfoAsync = GWT.create(DojoRoomService.class);
		vPanel = new VerticalPanel();
		userList = new FlexTable();	
		vPanel.add(userList);

		Timer time = new Timer(){
			public void run(){
				updateUserListFromServerAndUpdateClientInterface();
			}
		};

		time.scheduleRepeating(REFRESH_TIME);	
		initWidget(vPanel);
	}
	
	private void updateUserListFromServerAndUpdateClientInterface() {

		AsyncCallback<List<String> > callback = new AsyncCallback<List<String> >() {
			public void onFailure(Throwable caught) {

			}

			public void onSuccess(List<String> result) {
				while(userList.getRowCount() > 0)
					userList.removeRow(0);
				
				int i = 0;
				userList.setText(i++, 0, "User_List:");

				if(result != null){
					for (String username : result) {
						userList.setText(i++, 0, username);
					}
				}
			}
		};

		roomInfoAsync.getUserListFromRoom(dojoRoomName, callback);
	}
	

}
